package com.polaris.live.popup.party

import androidx.activity.viewModels
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.lxj.xpopup.core.DrawerPopupView
import com.polaris.live.R
import com.polaris.live.adapter.LiveDrawerAdapter
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.databinding.PopupLivePartyDrawerBinding
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.viewmodel.live.LivePartyDrawerViewModel

/**
 * LiveDrawerPopup
 *
 * @author Created by 半仙 on 2023/10/9/009 21:12
 */
class LivePartyDrawerPopup(
    context: FragmentActivity,
    private val onToLive: (DisplayUserBean) -> Unit,
    private val onToParty: () -> Unit,
) : DrawerPopupView(context) {

    private lateinit var mBinding: PopupLivePartyDrawerBinding

    override fun getImplLayoutId(): Int {
        return R.layout.popup_live_party_drawer
    }

    private val mViewMode by context.viewModels<LivePartyDrawerViewModel>()
    private val mAdapter by lazy { LiveDrawerAdapter() }

    override fun onCreate() {
        super.onCreate()

        mBinding = PopupLivePartyDrawerBinding.bind(popupImplView)
        val layout = mBinding.root.layoutParams
        layout.width = 316.autoDp
        mBinding.root.layoutParams = layout
        mBinding.refresh.apply {
            recycler.layoutManager =
                GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false)
            attachedAdapter(mAdapter, mViewMode).observe(
                this@LivePartyDrawerPopup,
                mViewMode.livesLiveData
            )
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position)

            onToLive.invoke(item)
        }
        mBinding.toParty.setOnSingleClickListener {
            onToParty.invoke()
        }
        chageToParty()
    }

    fun chageToParty() {
        if (this::mBinding.isInitialized) {
            mBinding.toParty.visibility =
                if (PartyUserStateUtil.inTheGame || PartyUserStateUtil.inTheGameSeat || PartyUserStateUtil.inTheMaiSeat) {
                    GONE
                } else {
                    VISIBLE
                }
        }

    }

    override fun onShow() {
        super.onShow()

        mBinding.refresh.autoRefresh()
    }
}